import { Avatar, Button, Col, Descriptions, Flex, Modal, Row, Space, Timeline, Typography } from "antd";
import DetailPageContainer from "../components/DetailPageContainer";
import styles from "./index.module.less";
import { InfoCircleFilled } from "@ant-design/icons";
import { MAIN_PRIMARY_COLOR } from "@/enums";
import { ProForm, ProFormInstance, ProFormText } from "@ant-design/pro-components";
import { useEffect, useRef, useState } from "react";
import cs from "classnames";
import useUrl from "@/hooks/useUrl";
import { useRequest } from "ahooks";
import { getLogisticsInfo, getOrderDetail } from "@/api/modules/transactionManagement";
import Loading from "@/components/Loading";
import { isEmpty, map, filter, cloneDeep } from "lodash";
import dayjs from "dayjs";
const { Paragraph, Text } = Typography;

export default () => {
	const [open, setOpen] = useState(false);
	const { query } = useUrl();
	const order_id = query.get("order_id");
	const { data, loading } = useRequest(getOrderDetail, { defaultParams: [{ order_id }] });
	const { data: data2, loading: loading2, runAsync } = useRequest(getLogisticsInfo, { manual: true });
	const detailData = data?.data ?? {};
	const logisticsList = data2?.data ?? [];

	useEffect(() => {
		if (!isEmpty(detailData?.logisticsInfo)) {
			const ids = map(detailData?.logisticsInfo, "waybill_id");
			runAsync({ waybill_ids: ids });
		}
	}, [detailData]);

	// console.log("========data2:", detailData, logisticsList);

	const items = [
		{
			key: "1",
			label: "订单编号",
			children: (
				<Paragraph className={styles.copy} copyable={{ icon: <a>复制</a> }}>
					{detailData?.order_id}
				</Paragraph>
			)
		},
		{
			key: "2",
			label: "收货信息",
			children: (
				<Text ellipsis={{ tooltip: true }}>
					{`
						${detailData?.receiver_info?.name}，
						${detailData?.receiver_info?.mobile}，
						${detailData?.receiver_info?.province}
						${detailData?.receiver_info?.city}
						${detailData?.receiver_info?.county}
						${detailData?.receiver_info?.address}
					`}
				</Text>
			),
			span: 2
		},
		{
			key: "3",
			label: "微信交易号",
			children: detailData?.wx_transaction_id && (
				<Paragraph className={styles.copy} copyable={{ icon: <a>复制</a> }}>
					{detailData?.wx_transaction_id}
				</Paragraph>
			)
		},
		{
			key: "4",
			label: "付款时间",
			children: detailData?.pay_time,
			span: 2
		}
	];

	const formRef = useRef<ProFormInstance | undefined>();

	const handleChangeOrderNumberSubmit = () => {
		formRef.current?.validateFieldsReturnFormatValue?.()?.then(values => {});
	};
	//修改单号
	const handleChangeOrderNumber = () => {
		setOpen(true);
	};

	const getItem2 = (itemData: any) => {
		console.log(itemData, '<==========itemData')
		const products = filter(
			map(itemData?.spec_ids, item => {
				const target = detailData?.itemsList?.find(i => i?.spec_id === item);

				if (!target) return null;
				return {
					icon: target?.product_snapshot?.product_thumbnail,
					name: target?.product_snapshot?.product_name,
					count: target?.spec_num
				};
			}),
			ii => Boolean(ii)
		);
		return [
			{
				key: "1",
				label: "物流单号",
				children: (
					<Space size={10}>
						<span>{itemData?.waybill_id}</span>
						{/* <a onClick={handleChangeOrderNumber}>修改单号</a> */}
					</Space>
				),
				span: 3
			},
			{
				key: "2",
				label: "物流名字",
				children: itemData?.delivery_name,
				span: 3
			},
			{
				key: "3",
				label: "发货时间",
				children: itemData?.created_at,
				span: 3
			},
			{
				key: "4",
				label: "发货方式",
				children: itemData?.send_type,
				span: 3
			},
			{
				key: "5",
				label: "包裹中的商品",
				children: (
					<Space direction="vertical" size={16}>
						{map(products, item => {
							return (
								<Space size={10}>
									<Avatar src={item?.icon} size={48} />
									<Flex vertical justify="space-between" align="flex-start" style={{ width: "260px" }}>
										<Text className={styles.list_name} ellipsis={{ tooltip: true }}>
											{item?.name}
										</Text>
										<span>x {item?.count}</span>
									</Flex>
								</Space>
							);
						})}
					</Space>
				),
				span: 3
			}
		];
	};

	return (
		<Loading isHeight100 loading={loading || loading2}>
			<>
				<DetailPageContainer className={styles.container} routeItem={{ title: "查看物流", className: styles.active }}>
					<div className={styles.info}>
						<Descriptions items={items} contentStyle={{ backgroundColor: "transparent" }} />
					</div>
					<div className={styles.title}>包裹明细</div>
					{map(detailData?.logisticsInfo, (item, index) => {
						const logisticsItem = logisticsList?.find(i => i?.waybill_id === item?.waybill_id);
						const list = cloneDeep(logisticsItem?.path_item_list)?.reverse() ?? [];
						console.log("==========logisticsItem:", list);

						return (
							<div className={styles.content} key={index}>
								<div className={styles.left}>
									<div className={styles.content_title}>发货信息</div>
									<Descriptions items={getItem2(item)} contentStyle={{ backgroundColor: "transparent" }} />
								</div>
								<div className={styles.right}>
									<div className={styles.content_title}>物流动态</div>
									{isEmpty(list) ? (
										<div>暂无物流轨迹信息</div>
									) : (
										<Timeline
											mode={"left"}
											className={styles.time_line}
											items={map(list, (item, index) => {
												console.log("===========index:", index === 0);
												return {
													children: (
														<Space direction="vertical" size={5}>
															<div className={cs([styles.detail_gray, index === 0 && styles.detail])}>{item?.action_msg}</div>
															<Space size={30} className={styles.date}>
																<span>操作时间: {dayjs(item?.action_time * 1000).format("YYYY-MM-DD HH:mm:ss")}</span>
																{/* <span>回传时间: 2024-06-04 17:36:26</span> */}
															</Space>
														</Space>
													)
												};
											})}
										/>
									)}
								</div>
							</div>
						);
					})}
				</DetailPageContainer>
				<Modal
					width={640}
					open={open}
					footer={
						<Flex justify="center">
							<Button type="primary" onClick={handleChangeOrderNumberSubmit}>
								确认修改
							</Button>
						</Flex>
					}
					onCancel={() => {
						setOpen(false);
					}}
					destroyOnClose
					title="修改运单号"
				>
					<div className={styles.dialog_wrap}>
						<div className={styles.tips}>
							<InfoCircleFilled style={{ color: MAIN_PRIMARY_COLOR, fontSize: "16px", marginRight: "3px" }} />
							同一笔订单最多可修改3次运单号，您已修改0次，还可以修改3次
						</div>
						<ProForm submitter={false} className={styles.dialog_form} formRef={formRef}>
							<Row gutter={10}>
								<Col span={12}>
									<ProFormText name="1" placeholder={"请输入物流单号"} rules={[{ required: true, message: "" }]} />
								</Col>
								<Col span={12}>
									<ProFormText name="1" placeholder={"输入物流公司"} rules={[{ required: true, message: "" }]} />
								</Col>
							</Row>
						</ProForm>
					</div>
				</Modal>
			</>
		</Loading>
	);
};
